/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pv168.confusinglibrary.database;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;

/**
 *
 * @author GNeps
 */
public abstract class DBCall<T> {

    private DataSource dataSource;
    protected Connection conn;
    private static final Logger logger = Logger.getLogger(DBCall.class.getName());

    public DBCall(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public abstract T makeCall() throws SQLException;

    public T call() {
        try {
            conn = dataSource.getConnection();

            return makeCall();
        } catch (SQLException ex) {
            String errMsg = conn == null ? "Error when connecting to DB" : "Error when communicating with DB";
            logger.log(Level.SEVERE, errMsg, ex);
            throw new RuntimeException(errMsg, ex);
        } finally {
            DBUtils.closeQuietly(conn);
        }
    }
}
